#include "stdafx.h"
#include "CScrLanguage.h"

CLListEx<CVariable*>	CVariables::s_VarList;
CLListEx<CVariable*>	CVariables::s_LVarList;
CList<CVariable>		CVariables::s_pVarList;
CCatalogue<CVariable>	CVariables::s_pVarCatalogue;
int						CVariables::s_nNumVars;
int						CVariables::s_nNumLVars;
CVariable			*	CVariables::s_pLastFoundVar;
CVariable			*	CVariables::s_pLastFoundLVar;

bool CVariables::LoadFromFile(const char *szFilePath)
{
	if(FILE *hFile = OpenFile(szFilePath, "rt"))
	{
		try
		{
			while(char *szStr = GetConfigLine(hFile))
			{
				char * szOffset = strtok(szStr, " \t"),
					 * szType = strtok(NULL, " \t"),
					 * szArraySize = strtok(NULL, " \t"),
					 * szIsTimer = strtok(NULL, " \t"),
					 * szName = strtok(NULL, " \t");

				if(!IsStringInt(szOffset)) throw(SCRambl.BuildText(SCRambl.GetText("VARIABLES", "M100"), NULL, 0, "%s", szOffset));
				if(!IsStringInt(szArraySize)) throw(SCRambl.BuildText(SCRambl.GetText("VARIABLES", "M101"), NULL, 0, "%s", szArraySize));

				bool bIsTimer;
				if(IsStringInt(szIsTimer)) bIsTimer = StringToInt(szIsTimer) != 0;
				else bIsTimer = !strnicmp(szIsTimer, "true", 4);
				
				int offset = StringToInt(szOffset);
				int array_size = StringToInt(szArraySize);
				auto pType = CSyntax::GetTypeByID(szType);

				if(!pType) throw(SCRambl.BuildText(SCRambl.GetText("VARIABLES", "M102"), NULL, 0, "%s", szType));

				auto pVar = CVariables::Add(szName, pType, offset, array_size, true);
				pVar->IsPredefined(true);
				pVar->IsTimer(bIsTimer);
			}
			CloseFile(hFile);
			return true;
		}
		catch(const char * e)
		{
			throw(SCRambl.BuildText(SCRambl.GetText("GENERAL", "FERR"), NULL, 0, "%s", e, szFilePath));
		}
	}
	else throw(SCRambl.BuildText(SCRambl.GetText("GENERAL", "OERR"), NULL, 0, "%s", szFilePath));
	return false;
}